package com.example.frickytest;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.view.*;
import android.view.View.OnClickListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;

public class IPCActivity extends Activity implements OnClickListener{
	private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
	private Button btn, btn2;
	private IBinder ib = null;
	
    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		btn = new Button(this);
		btn.setId(101);
		btn.setText("run service");
		btn.setOnClickListener(this);
//		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(135, 50);
//		param.topMargin = 10;
		layout.addView(btn, new LinearLayout.LayoutParams(WC, WC));
		btn2 = new Button(this);
		btn2.setId(102);
		btn2.setText("Exit");
		btn2.setOnClickListener(this);
		layout.addView(btn2, new LinearLayout.LayoutParams(WC, WC));
		setContentView(layout);
		// ---------------------------------------
		Thread.currentThread().setName(
				Thread.currentThread().getName() + "-ac01");
		// -----------------------------
		bindService(new Intent("com.example.frickytest.REMOTE_SERVICE"), mConnection,
				Context.BIND_AUTO_CREATE);
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder ibinder) {
			ib = ibinder;
		}

		public void onServiceDisconnected(ComponentName name) {
		}
	};

	public void onClick(View v) {
		switch (v.getId()) {
		case 101:
			Parcel pc = Parcel.obtain();
			Parcel pc_reply = Parcel.obtain();
			try {
				ib.transact(2, pc, pc_reply, 0);
				setTitle(pc_reply.readString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case 102:
			finish();
			break;
		}
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_ipc, menu);
        return true;
    }
}
